<?php


	namespace app\services;


	use app\model\Relationships;
	use think\Exception;
	use think\facade\Db;

	class RelationshipServices
	{

		/**
		 * 新增
		 *
		 * @param     $uid
		 * @param int $target_id 目标id,即绑定到该用户下
		 * @param
		 *
		 * @throws
		 *
		 */
		public function addNode ($uid, $target_id = 0) {
			$targetItem = Relationships::where('uid', '=', $target_id)->find();
			if ($target_id && $targetItem) {
				//我的左值 = 父级的右值
				$left_no = $targetItem->right_no;
				//我的右值 = 我的左值(父级的右值) + 1
				$right_no = $targetItem->right_no + 1;
				//我的等级 = 父级的等级 + 1;
				$level = $targetItem->level + 1;
				//插入我的数据

				//中途插入一个人进来,等于说是所有的节点的左右值都要自增2
				//左值 > 目标的右值 的左值自增2
				Relationships::where('left_no', '>', $targetItem->right_no)->inc('left_no', 2)->update();
				//右值 > 目标的右值 的右值自增2
				Relationships::where('right_no', '>=', $targetItem->right_no)->inc('right_no', 2)->update();
				//绑定关系
				Relationships::create([
					'uid'      => $uid,
					'pid'      => $target_id,
					'left_no'  => $left_no,
					'right_no' => $right_no,
					'level'    => $level
				]);
			} else {
				//新增,顶级用户
				$maxRight = Relationships::max('right_no');
				$maxRight = $maxRight ? $maxRight : 0;
				$left_no = $maxRight + 1;
				$right_no = $maxRight + 2;
				$level = 0;
				Relationships::create([
					'uid'      => $uid,
					'left_no'  => $left_no,
					'right_no' => $right_no,
					'level'    => $level
				]);
			}
		}


		public function delNode ($uid) {



			Db::startTrans();
			try {
				$source = Relationships::where('uid','=',$uid)->find();
				if($source){
					$width = ($source->right_no - $source->left_no) + 1;

					$row = Relationships::where([
						['left_no', '>', $source->left_no],
						['right_no', '<', $source->right_no]
					])->update(['status' => 1]);
				}
			}catch (Exception $exception){
				Db::rollback();
				return $exception->getMessage();
			}

			$item = Relationships::where('uid', '=', $uid)->find();
			//子节点的宽度,就是其他节点左右值需要减少的值,受影响的节点就是删除节点的右边节点
			$width = ($item->right_no - $item->left_no) + 1;
			//删除节点及子节点
			//节点的全部下线,左值>=我的左值且右值<=我的右值;
			Relationships::where([
				['left_no', '>=', $item->left_no],
				['right_no', '<=', $item->right_no]
			])->delete();

			//其他节点 左值 > 删除节点的右值, 右值 >= 删除节点的右值
			Relationships::where('left_no', '>', $item->right_no)->dec('left_no', $width)->update();
			Relationships::where('right_no', '>=', $item->right_no)->dec('right_no', $width)->update();

		}


	}
